<template>
  <div class="page-container">
    <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>通用促销</el-breadcrumb-item>
        <el-breadcrumb-item>组合促销</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters" :rules="filtersRules">
        <el-row class="times">
            <el-form-item label="活动时间：" prop="startTime">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion"
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束时间"
                class="input_postion"
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>
             <el-form-item label="活动类型：" prop="frontPromType">
              <el-select v-model="filters.frontPromType" placeholder="全部" clearable>
                <el-option label="x元y件" value="22"></el-option>
                <el-option label="x件付y件" value="23"></el-option>
              </el-select>
            </el-form-item>
        </el-row>
        <el-row class="search-input">
          <el-form-item label="创建人：" prop="creatorNameForSearch">
              <el-input v-model="filters.creatorNameForSearch" placeholder="创建人" clearable maxlength="80"></el-input>
          </el-form-item>
          <el-form-item label="活动名称：" prop="promName" class="mr25">
            <el-input v-model="filters.promName" placeholder="活动名称" clearable maxlength="80"></el-input>
          </el-form-item>
          <el-form-item label="活动ID：" prop="promotionCode">
            <el-input v-model="filters.promotionCode" placeholder="活动ID" clearable maxlength="80"></el-input>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button :plain="true" :label="$t('action.reset')" class="resetButton" icon="el-icon-refresh" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="el-icon-search" label="搜索"
              class="searchButton"
              @click="findPage"
            />
          </el-form-item>

          <el-form-item>
            <kt-button
              label="创建活动"
              @click="createPage()"

              class="searchButton"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!-- 列表 -->
    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tabMapOptions"
          :key="item.key"
          :label="item.label"
          :name="item.key"
        ></el-tab-pane>
      </el-tabs>
      <!-- jic table表格-->
      <div class="toolbar">
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <!--表格内容栏-->
      <jic-table
        ref="JicTable"
        :height="350"
        :data="pageResult"
        :operationWidth="450"
        :totalSize="totalSize"
        :columns="filterColumns"
        :showCopyDataOperation="true"
        :showCopyLinkOperation="false"
        :showDetailOperation="true"
        :showBatchDelete="false"
        :loading="loading"
        :btnList="btnList"
        @findPage="findPage"
        @handleDetail="handleDetail"
        @colsePromotion="colsePromotion"
        @updatePromotion="updatePromotion"
        @handleCopyData="handleCopyData"
        @submitReview="submitReview"
        @deletePromotion="deletePromotion"
        @review="review"
      ></jic-table>
    </div>
    <!-- 审核弹窗 -->
    <el-dialog title="审核" :visible.sync="verifyDialogFormVisible" class="el-dialog-style">
      <el-form :model="verifyForm">
        <el-form-item>
          <el-input v-model="verifyForm.auditRemark" autocomplete="off" type="textarea" rows="6" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="reviewDialog(4)" size="mini" class="cancelButton" >审核拒绝</el-button>
        <el-button type="primary" @click="reviewDialog(11)" size="mini" class="searchButton">审核通过</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import JicTable from "@/views/Core/LotteryTable";
import { format } from "@/utils/datetime";
import marketRequest from "@/market/request/marketRequest";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
 import tabPane from "./components/TabPaneComplex";
 //import tabPane from "./components/TabPaneGift";
export default {
  name: "Tab",
  components: {
    tabPane,
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var checkStartTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.endTime == null ||
        typeof this.filters.endTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() > new Date(this.filters.endTime).getTime()
      ) {
        callback(new Error("开始时间不能大于结束时间"));
      }
      this.$refs.filters.clearValidate("endTime");
      callback();
    };
    var checkEndTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.startTime == null ||
        typeof this.filters.startTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() < new Date(this.filters.startTime).getTime()
      ) {
        callback(new Error("结束时间不能小于开始时间"));
      }
      this.$refs.filters.clearValidate("startTime");
      callback();
    };
    return {
      channelOption:[],
      dataFormRules:{
        //templateName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
      filtersRules: {
        // promName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // creatorNameForSearch: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        startTime: [{ validator: checkStartTime, trigger: "change" }],
        endTime: [{ validator: checkEndTime, trigger: "change" }]
      },
      useTempDialogVisible: false,
      tableData: [],
      tableDataTotal: 0,
      dataForm: {
        id: null,
        promType: 6, //组合促销
        templateName: null
      },
      verifyForm: {}, //审核弹窗form
      formLabelWidth: "100px",
      tabMapOptions: [
        { label: "全部", key: "0" },
        { label: "进行中", key: "5" },
        { label: "已结束", key: "8" },
        { label: "已过期", key: "6" },
        { label: "已关闭", key: "7" },
        { label: "未开始", key: "3" },
        { label: "待提交", key: "1" },
        { label: "待审核", key: "2" },
        { label: "审核未通过", key: "4" },
        { label: "活动草稿", key: "9" }
      ],
      columns: [
        { prop: "promotionCode", label: "活动ID", minWidth: 300 },
        { prop: "promName", label: "活动名称", minWidth: 200 },
        {
          prop: "startTime",
          label: "活动时间",
          minWidth: 360,
          formatter: function(row, column, cellValue, index) {
            //活动开始结束时间拼接
            if (row.startTime != null && row.endTime != null) {
              return row.startTime + " 至 " + row.endTime;
            }
          }
        },
        {
          prop: "frontPromType",
          label: "活动类型",
          minWidth: 100,
          formatter: function(row, column, cellValue, index) {
            //活动类型 22：X元Y件，23: X件付Y件
            if (row.frontPromType == 22) {
              return "X元Y件";
            } else if (row.frontPromType == 23) {
              return "X件付Y件";
            }else if (row.frontPromType == 21) {
              return "全部";
            }
          }
        },
        { prop: "channelCodes", label: "活动渠道", minWidth: 200 },
        {
          prop: "status",
          label: "活动状态",
          minWidth: 100,
          formatter: function(row, column, cellValue, index) {
            //状态 1 待提交 2 待审核 3 审核不通过 4 进行中 5 已过期 6 已关闭 7 未开始
            if (row.status == "1") {
              return "待提交";
            } else if (row.status == "2") {
              return "待审核";
            } else if (row.status == "4") {
              return "审核不通过";
            } else if (row.status == "5") {
              return "进行中";
            } else if (row.status == "6") {
              return "已过期";
            } else if (row.status == "7") {
              return "已关闭";
            } else if (row.status == "8") {
              return "已结束";
            } else if (row.status == "3") {
              return "未开始";
            } else if (row.status == "9") {
              return "活动草稿";
            }
          }
        },
        { prop: "creatorName", label: "创建人", minWidth: 200 },
        { prop: "createTime", label: "创建时间", minWidth: 220 }
      ],
      //列表按钮
      btnList: [
        {
          customLabel: "关闭",
          isShowMethod: "3,5",
          method: "colsePromotion"
        },
        {
          customLabel: "编辑",
          isShowMethod: "1,4,9",
          method: "updatePromotion"
        },
        {
          customLabel: "删除",
          isShowMethod: "1,9",
          method: "deletePromotion"
        }
      ],
      pageResult: {},
      filterColumns: [],
      totalSize: 0,
      pageRequest: {},
      loading: true,
      activeName: "0",
      size: "small",
      filters: {
        promName: null,
        promotionCode: null,
        id: "",
        promType: 6,
        creatorNameForSearch: "",
        startTime: "",
        endTime: "",
        frontPromType: "",
        promotionCode:'',
      },
      flag: false,
      form: {
        region: ""
      },
      templateLoading:false,
      createdTimes: 0,
      size: "small",
      merchantIds: [{ merchantId: null, label: "请选择" }],
      storeIds: [{ storeId: null, label: "请选择" }],
      verifyDialogFormVisible: false, //审核弹窗
      verifyForm: {}
    };
  },
  methods: {
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },
    createPage() {
      this.$router.push({ path: "/ComplexPromotionCreate/0/1" });
    },
    // 获取分页数据
    findPage: function(data) {
      //子组件传过来的分页参数 data.start 当前页 data.limit 当前页总条数
      this.loading = true;
      if (data != null && data.start != null) {
        if (data.start != null) {
          this.pageRequest.pageNum = data.start;
        }
        if (data.limit != null) {
          this.pageRequest.pageSize = data.limit;
        }
      }
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.filters.promType = 6;
      this.utils.request.promotionList(this_.filters, function(res) {
        this_.loading = false;
        if (res.data.list.length < 1) {
          res.data.rows = [];
          res.data.total = 0;
        }
        this_.$refs.JicTable.findPage({
          content: res.data.list,
          total: res.data.totalCount
        });
      });
    },
    //查看
    handleDetail: function(data) {
      this.$router.push({ path: "/ComplexPromotionInfo/" + data.row.id });
    },
    //编辑
    updatePromotion: function(data) {
      this.$router.push({ path: "/ComplexPromotionCreate/" + data.row.id + "/1"});
    },
    //复制抽奖活动
    handleCopyData: function(data) {
      this.$confirm("确定要复制该活动？", "提示", {
        type: "warning",
        closeOnClickModal: false,
      })
        .then(() => {
          if (data != null && data.row != null) {
            var params = {};
            params.id = data.row.id;
            var this_ = this;
            marketRequest.promotionDeepCopy(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "复制成功 ", type: "success" });
                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          }
        })
        .catch(() => {});
    },
    // 删除活动
    deletePromotion: function(data) {

      this.$confirm("确定要执行删除操作么？删除后不可恢复!", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        if (data != null && data.row != null) {
          var params = {};
          params.id = data.row.id;
          var this_ = this;
          this.utils.request.promotionDelete(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "操作成功", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({ message: "操作失败, " + res.msg, type: "error" });
            }
          });
        }
      }) .catch(() => {});
    },
    //关闭活动
    colsePromotion: function(data) {
      let msg = ''
      if(data.row.status == 5){
        msg = '该活动正在进行中，确定要关闭它？关闭后不可再次开启。'
      }else{
        msg = '该活动即将进行，确定要关闭它？关闭后不可再次开启。'
      }
      let params = {};
      params.id = data.row.id;
      params.status = 7; //关闭状态为7
      var this_ = this;
      this.$confirm(msg, "提示", {
        type: "warning",
        closeOnClickModal: false, })
        .then(() => {
          this.utils.request.promotionUpdateStatus(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "活动已关闭 ", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({
                message: "操作失败, " + res.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {});
    },
    //提交审核
    submitReview: function(data) {
      let that = this;
      const loading = this.$loading({
        lock: true,
        text: "小的正在努力加载中......",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.8)"
      });
      this.utils.request.promotionUpdateStatus(
        { id: data.row.id, status: 2 },
        res => {
          loading.close();
          that.$message({ message: "提交审核成功", type: "success" });
          that.findPage();
        }
      );
    },
    //审核
    review: function(data) {
      this.verifyDialogFormVisible = true;
      this.verifyForm.id = data.row.id;
    },
    //审核
    reviewDialog: function(data) {
      if (
        this.verifyForm.auditRemark == null ||
        this.verifyForm.auditRemark == ""
      ) {
        this.$message({ message: "审核意见不能为空", type: "error" });
        return false;
      }
      let that = this;
      this.verifyForm.status = data;
      that.utils.request.promotionUpdateStatus(this.verifyForm, res => {
        if (res.code == "0000") {
          that.verifyDialogFormVisible = false;
          that.$message({ message: "审核完成", type: "success" });
          that.findPage();
        } else {
          that.$message({ message: "审核失败", type: "error" });
        }
      });
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    //重置
    resetForm(formName) {

      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.findPage();
      }
    },
    getPromotionList() {
      this.$refs.child[0].listQuery.pageNo = 1;
      this.$refs.child[0].getList();
    },
  },
  watch: {
    activeName(val) {
      if (val != "0") {
        this.filters.status = val;
      } else {
        this.filters.status = null;
      }
      this.findPage();
    }
  },
  created() {
    const tab = this.$route.query.tab;
    if (tab) {
      this.activeName = tab;
    }
  },
  mounted() {
    this.initColumns();
  }
};
</script>

<style scoped lang="scss">
</style>
